<template>
  <div class="other-product">
    <!-- 添加产品弹窗 -->
    <el-dialog
      title="添加附加产品"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form :model="productForm" :rules="rules" ref="productForm" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="productForm.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="加急" value="加急"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="productForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="productForm.status">
            <el-radio label="上线">上线</el-radio>
            <el-radio label="下线">下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加按钮 -->
    <el-button
        type="primary"
        class="add-button"
        round
        @click="showAddDialog"
        style="background-color: #803f7d; border-color: #000000;">
      <i class="el-icon-plus" style="margin-right: 3px;"></i>添加新的产品
    </el-button>
    
    <!-- 搜索框 -->
    <el-input
      v-model="searchKeyword"
      placeholder="请输入搜索内容"
      clearable
      class="search-input"
    >
      <el-button slot="append" icon="el-icon-search" @click="handleSearch"/>
    </el-input>

    <!-- 产品列表表格 -->
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="name" label="附加产品名称"/>
      <el-table-column prop="type" label="类型"/>
      <el-table-column prop="remark" label="备注"/>
      <el-table-column prop="createTime" label="添加时间">
        <template slot-scope="scope">
          {{ scope.row.createTime ? new Date(scope.row.createTime).toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import axios from '@/utils/request'

export default {
  data() {
    return {
      // 添加新的数据属性
      dialogVisible: false,
      productForm: {
        name: '',
        type: '',
        remark: '',
        status: '上线',
        dialogTitle: '添加附加产品',
      isEdit: false,
      editId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      // 保留原有的数据
      searchKeyword: '',
      tableData: [
        // ... 原有的表格数据
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  methods: {
    // 添加新的方法
    showAddDialog() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '添加附加产品'
      this.dialogVisible = true
      this.$refs.productForm?.resetFields()
    },
    // 编辑按钮处理
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑附加产品'
      this.dialogVisible = true
      // 填充表单数据
      this.productForm = {
        name: row.name,
        type: row.type,
        remark: row.remark,
        status: row.status === 1 ? '上线' : '下线'
      }
    },

    // 删除按钮处理
    handleDelete(row) {
      this.$confirm('确定要删除该产品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await axios.delete(`/admin/otherProduct/${row.id}`)
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.fetchTableData()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除产品出错：', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },
    cancelAdd() {
      this.$refs.productForm?.resetFields()
      this.dialogVisible = false
    },
    confirmAdd() {
      this.$refs.productForm.validate(async valid => {
        if (valid) {
          try {
            const data = {
              name: this.productForm.name,
              type: this.productForm.type,
              remark: this.productForm.remark,
              status: this.productForm.status === '上线' ? 1 : 0
            }

            let res
            if (this.isEdit) {
              res = await axios.put(`/admin/otherProduct/${this.editId}`, data)
            } else {
              res = await axios.post('/admin/otherProduct', data)
            }
            
            if (res.code === 1) {
              this.$message.success(this.isEdit ? '修改成功' : '添加成功')
              this.dialogVisible = false
              this.$refs.productForm.resetFields()
              this.fetchTableData()
            } else {
              this.$message.error(res.msg || (this.isEdit ? '修改失败' : '添加失败'))
            }
          } catch (error) {
            console.error(this.isEdit ? '修改产品出错：' : '添加产品出错：', error)
            this.$message.error(this.isEdit ? '修改失败' : '添加失败')
          }
        }
      })
    },
    // 添加获取表格数据的方法
    async fetchTableData() {
      try {
        const res = await axios.get('/admin/otherProduct/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.searchKeyword
          }
        })
        
        if (res.code === 1) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      } catch (error) {
        console.error('获取数据失败：', error)
        this.$message.error('获取数据失败')
      }
    }
  },
  
  // 添加生命周期钩子，组件创建时获取数据
  created() {
    this.fetchTableData()
  }
}
</script>

<style scoped>
.other-product {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
  color: #666;
}

.add-button {
  margin-bottom: 20px;
  float: left;  /* 添加浮动属性 */
}

.search-input {
  width: 300px;
  float: right;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style>